package com.zpark.cloud.alibaba.service.impl;

import com.zpark.cloud.alibaba.entity.Order;
import com.zpark.cloud.alibaba.feign.IAccountFeign;
import com.zpark.cloud.alibaba.feign.IStorageFeign;
import com.zpark.cloud.alibaba.mapper.IOrderMapper;
import com.zpark.cloud.alibaba.service.IOrderService;
import com.zpark.cloud.alibaba.utils.ResponseResult;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @PackageName: com.zpark.cloud.alibaba.service.impl
 * @ClassName: OrderServiceImpl
 * @Description:
 * @author: RZS
 * @date: 2023/6/28  16:52
 */
@Service
@Slf4j
public class OrderServiceImpl implements IOrderService {

    @Autowired
    private IOrderMapper orderMapper;

    @Autowired
    private IAccountFeign accountFeign;

    @Autowired
    private IStorageFeign storageFeign;

    /**
     * 下单流程：
     *      1、创建订单（订单状态：未完成）
     *      2、调用库存微服务修改库存
     *      3、调用账户微服务修改账户
     *      4、修改订单状态为已完成
     */
    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public Integer addOrder(Order order) {
        log.info("----->开始新建订单");
        // 将order的状态设为0
        order.setStatus(0);
        // 创建订单
        int row = orderMapper.insert(order);
        //2 扣减库存
        log.info("----->订单服务开始调用库存服务，开始扣减库存");
        storageFeign.changeStorage(order.getProductId(), order.getCount());
        log.info("----->订单微服务开始调用库存，扣减库存结束");
        //3 扣减账户
        log.info("----->订单服务开始调用账户服务，开始从账户扣减商品金额");
        accountFeign.changeAccountResidue(order.getUserId(), order.getMoney());
        log.info("----->订单微服务开始调用账户，账户扣减商品金额结束");
        //4 修改订单状态，从零到1,1代表已经完成
        log.info("----->修改订单状态开始");
        Integer row1 = orderMapper.updateOrderByUserId(order.getUserId());
        log.info("----->修改订单状态结束");
        log.info("----->下订单结束了------->");

        return row1;
    }
}
